package com.atguigu.grainmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.grainmall.search.config.GrainmallElasticSearchConfig;
import com.atguigu.grainmall.search.constant.EsConstant;
import com.atguigu.grainmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author shiyuan
 * @Date 2023/2/21 13:40
 * @Version 1.0
 * 商品保存
 **/
@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 商品上架
     *
     * @param skuEsModels
     * @return
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        // 1. 保存到es
        // 1.1 给es中建立索引 -> product 建立映射关系

        // 2. 给es中保存数据 使用bulk进行批量操作 BulkRequest bulkRequest, RequestOptions options 使用循环 通过bulkRequest.add() 进行保存
        BulkRequest bulkRequest = new BulkRequest();
        // 构造保存请求
        for (SkuEsModel model : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 指定按照那个id存储
            indexRequest.id(model.getSkuId().toString());
            // 指定存储类型   --Json
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GrainmallElasticSearchConfig.COMMON_OPTIONS);

        // todo 如果批量执行保存出错 进行处理
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成：{}", collect,"返回数据:{}",bulk.toString());

        return b;
    }
}
